import React from 'react';
import {Table, Field, Input, Select, Form, Box, Button, Card, DatePicker, Message, Radio, Collapse,Upload, Switch, Dialog, Grid } from '@alifd/next';
import styles from './index.module.scss';

import {optionExamPaperList} from '@/api/ExamPaperAPI'
import {add} from '@/api/ExamPaperQuestionAPI'
import {upLoadImage} from '@/api/CommonAPI'
import {hanlderOptionNoName, getOptionValue, getOptionModel, removeItemById} from '@/utils/tool'
const {Row, Col} = Grid;
const FormItem = Form.Item;
const Panel = Collapse.Panel;
const formItemLayout = {
  colSpan: 12,
};

const formItemLayout_two = {
    colSpan: 6,
};
const formItemLayout_three = {
    colSpan: 4,
};

const DEFAULT_DATA = {
    id: '',
    type:'0',
    typeName:'0',
    courseId:'',
    courseCode:'',
    courseSmallName:'',
    examPaperId: '',
    examPaperCode: '',
    examPaperSmallName: '',
    main:'',
    answer:'',
    options:[],
    sort:'',
    state: '0',
    publishTime:'',
    createTime: '',
    createId: '',
    createName: '',
    updateTime: '',
    updateId: '',
    updateName: '',
    mainImage: [],
    answerImage: [],

  };

class AddExamPaperQuestion extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            postData: DEFAULT_DATA,
            visible: false,
            stateV:'',
            examPaperV: '',
            courseOptionList: [],
            examPaperOptionList:[],
            examPaperData:[],
            typeOptionList: [],
            stateOptionList: [],
            choiceData: [],
        };
        this.field = new Field(this, {
            parseName: true,
            values: {
                name:[''].map(i => {
                    return { input: i };
                })
            }
        });
    }

    
    // 初始化方法
    componentDidMount(){
        this.props.onRef(this)
    };

    // 1 打开弹框
    onOpen = (courseOption, quetionTypesData, quetionStatesData) => {
        this.resetForm(); 
        for(const i in quetionStatesData){
            const state = quetionStatesData[i]
            if(state.value == '0'){
                this.state.stateV = state.label
                break
            }
        }
        this.setState({
            courseOptionList: courseOption,
            typeOptionList: quetionTypesData,
            stateOptionList: quetionStatesData,
            postData: DEFAULT_DATA,
            visible: true,
        })
    };
    // 2 关闭弹框
    onClose = () => {
        this.setState({
            visible: false
        })
    };
    // 3 修改表单信息
    formChange = values => {
        this.setState({
            postData: values
        })
    };
    // 4 修改课程
    changeCourse = (courseId) => {
        const c = this.props.getCourseInfo(courseId);
        DEFAULT_DATA.courseId = courseId
        DEFAULT_DATA.courseCode = c.code
        DEFAULT_DATA.courseSmallName = c.smallName
        DEFAULT_DATA.examPaperId = '',
        DEFAULT_DATA.examPaperCode = '',
        DEFAULT_DATA.examPaperSmallName ='',
        optionExamPaperList(courseId).then((data)=>{
            if(data){
                this.setState({
                    examPaperData: data,
                    examPaperOptionList: hanlderOptionNoName(data),
                    examPaperV:'',
                    postData: DEFAULT_DATA,
                })
            }
        });
    }
    // 5 修改试卷
    changExamPaper = (v) => {
        for (const key in this.state.examPaperData) {
            const ch = this.state.examPaperData[key]
            if(ch.id == v){
                console.log('赋值成功', ch)
                DEFAULT_DATA.examPaperId = v;
                DEFAULT_DATA.examPaperCode = ch.examPaperCode;
                DEFAULT_DATA.examPaperSmallName = ch.smallName;
                this.setState({
                    postData: DEFAULT_DATA,
                    examPaperV: ch.smallName,
                })
                return
            }
        }
    }
    // 6 改变表单--题目类型
    changeFormQuestionType= (v, t, model) => {
        DEFAULT_DATA.type = model.value;
        DEFAULT_DATA.typeName = model.label;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };

    // 7 改变表单--排序
    changeFormSort= (v) => {
        DEFAULT_DATA.sort = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    // 8 改变表单--题干
    changeFormMain= (v) => {
        DEFAULT_DATA.main = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    // 9 改变表单--答案
    changeFormAnswer= (v) => {
        DEFAULT_DATA.answer = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    // 10 改变表单--备注
    changeFormRemark= (v) => {
        DEFAULT_DATA.remark = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    // 11 改变表单--分数
    changeFormScore= (v) => {
        DEFAULT_DATA.score = v;
        this.setState({
            postData: DEFAULT_DATA,
        })
    };
    /**
     * 上传附件
     * @param {*} info 
     */
    upLoadImageBegin = (info) => {
        // 1 调用上传API
        let filename = info.filename;
        console.log('info is:::', filename)
        upLoadImage( 'file', info.file).then((data)=>{
            if(data){
                // 2 处理 主干图片
                if(filename == 'mainImage'){
                    DEFAULT_DATA.mainImage.push(data)
                }
                // 3 处理 答案图片
                if(filename == 'answerImage'){
                    DEFAULT_DATA.answerImage.push(data)
                }        
                // 4 回显信息
                let onSuccessInfo = {
                    success: true,
                    uid: data.id,
                    url: data.url,
                }
                console.log('upLoadImageBegin DEFAULT_DATA is:::', DEFAULT_DATA)
                info.onSuccess(onSuccessInfo);
     
                // this.setState({
                //     postData: DEFAULT_DATA
                // })
            }
        });
    };
    // 删除图片信息
    onRemoveImage =(filename, info) =>{
        console.log('onRemoveImage info is:::', info)
        console.log('onRemoveImage filename is:::', filename)
    }
    // 删除图片信息
    onRemoveMainImage =(info) =>{
        console.log('onRemoveImage info is:::', info)
    }
    // 提交表单信息
    onSubmit = (values, errors) => {
        if (errors) {
          console.log('errors', errors);
          return;
        }
        // 处理折叠选择项目信息
        const zheDieValues = this.field.getValue('name');
        console.log('提交信息::zheDieValues:', zheDieValues);
        const ops = []
        zheDieValues.map(i => {
            ops.push(i.input) 
        })
        console.log('提交信息::ops:', ops);
        DEFAULT_DATA.options =  ops
        console.log('提交信息::DEFAULT_DATA:', DEFAULT_DATA);
        // 调用修改题目API接口
        add(DEFAULT_DATA).then((flag)=>{
            if(flag){
                Message.success('提交成功');
                this.resetForm(); // 清空表单源数据
                this.onClose();
                this.props.onFreshList();
            }else{
                return
            }
        });
    };
    /**
     * 重置表单
     */
    resetForm = ()=>{
        DEFAULT_DATA.id = '',
        DEFAULT_DATA.type ='',
        DEFAULT_DATA.typeName ='',
        DEFAULT_DATA.courseId ='',
        DEFAULT_DATA.courseCode ='',
        DEFAULT_DATA.courseSmallName ='',
        DEFAULT_DATA.examPaperId = '',
        DEFAULT_DATA.examPaperCode = '',
        DEFAULT_DATA.examPaperSmallName ='',
        DEFAULT_DATA.main ='',
        DEFAULT_DATA.answer ='',
        DEFAULT_DATA.options =[],
        DEFAULT_DATA.sort ='',
        DEFAULT_DATA.state = '0',
        DEFAULT_DATA.publishTime ='',
        DEFAULT_DATA.createTime = '',
        DEFAULT_DATA.createId = '',
        DEFAULT_DATA.createName = '',
        DEFAULT_DATA.updateTime = '',
        DEFAULT_DATA.updateId = '',
        DEFAULT_DATA.updateName = '',
        DEFAULT_DATA.mainImage = [],
        DEFAULT_DATA.answerImage = [],
        DEFAULT_DATA.remark = '',
        this.setState({
            DEFAULT_DATA,
        })
    }

    onPreview(info){
        console.log('onPreview:::', info);
    }
    /************************* 选择列表信息项 start ******************************** */
    getChoiceOptionsValues = () => {
        const zheDieValues = this.field.getValue('name');
        console.log('zheDieValues:::', zheDieValues);
    }
    // 新增选择列表信息项
    addItem(index){
        this.field.addArrayValue('name', index,{input: ''});
    }
    // 移除选择列表信息项
    removeItem(index) {
        console.log('删除了：：', index)
        this.field.deleteArrayValue('name',index);
    }
    // 构建
    input = (value, index) => <Input style={{width:'400px'}} {...this.field.init(`name.${index}.input`)} />;
    op = (value, index) => {
        return (<span>
            <Button type="primary" size='small' onClick={this.addItem.bind(this, index + 1)}>增加</Button>
            <Button  size='small' warning onClick={this.removeItem.bind(this, index)} style={{marginLeft: 4}}>删除</Button>
        </span>);
    }

    /************************* 选择列表信息项 end ******************************** */
    render(){
        const xDataSource = this.field.getValue('name');
        return (
            <div > 
                <Dialog title="新增试卷题目信息" visible={this.state.visible} footer ={false}  onClose={this.onClose} style={{width: '40%'}} >
                    <Card free className={styles.TwoColumnForm}>
                    <Card.Content>
                        <Form responsive fullWidth value={this.state.postData} labelAlign="top">

                            <FormItem {...formItemLayout_two} label="课程"  required requiredMessage="必填">
                                <Select name='courseId' placeholder="选择课程" dataSource= {this.state.courseOptionList || []}  onChange={this.changeCourse}  hasClear/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="试卷" required requiredMessage="必填">
                                <Select name='examPaperId' placeholder="请选择试卷" value={this.state.examPaperV} dataSource= {this.state.examPaperOptionList || []}  onChange={this.changExamPaper} hasClear/>
                            </FormItem>
                            <FormItem {...formItemLayout_three} label="题目类型"  required requiredMessage="必填">
                                <Select name='type' placeholder="请选择题目类型" dataSource= {this.state.typeOptionList || []} onChange={this.changeFormQuestionType} hasClear/>
                            </FormItem>
                            <FormItem {...formItemLayout_three} label="分数" required requiredMessage="必填">
                                <Input placeholder="请输入试题分数" name="score" onChange={this.changeFormScore} />
                            </FormItem>
                            <FormItem {...formItemLayout_three} label="排序" required requiredMessage="必填">
                                <Input placeholder="请输入试题排序" name="sort" onChange={this.changeFormSort} />
                            </FormItem>
                            <FormItem {...formItemLayout} label="题干" required requiredMessage="必填">
                                <Input.TextArea placeholder="请输入题目主干信息" name="main" onChange={this.changeFormMain} />
                            </FormItem>
                            <FormItem {...formItemLayout} label="选择题-选项列表">
                                <Collapse>
                                <Panel title="折叠选择项">
                                    <Table size='small' dataSource={xDataSource}>
                                        <Table.Column title="选择项内容" dataIndex="id" cell={this.input} />
                                        <Table.Column title="operation" cell={this.op} width={150} />
                                    </Table>
                                    </Panel>
                                </Collapse>
                            </FormItem>
                            <FormItem {...formItemLayout} label="答案" required requiredMessage="必填" >
                                <Input.TextArea placeholder="请输入题目主干信息" name="answer"  onChange={this.changeFormAnswer}/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="上传题干图片：">
                                <Upload.Card name="mainImage" listType="card"
                                    accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp"
                                    request={this.upLoadImageBegin}
                                    onRemove={this.onRemoveMainImage}
                                    defaultValue={this.state.mainImage}
                                    onPreview={this.onPreview}
                                    limit={2}
                                />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="上传答案图片：">
                                <Upload.Card name="answerImage" listType="card"
                                    accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp"
                                    request={this.upLoadImageBegin}
                                    onRemove={this.onRemoveImage}
                                    defaultValue={this.state.answerImage}
                                    limit={2}
                                />
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="状态" required requiredMessage="必填">
                                <Input value={this.state.stateV}  disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="发布时间">
                                <Input name="publishTime" disabled/>
                            </FormItem>

                            <FormItem {...formItemLayout} label="备注">
                                <Input.TextArea placeholder="请输入备注" name="remark" onChange={this.changeFormRemark}/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="创建人">
                                <Input name="createName" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="创建时间">
                                <Input name="createTime" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="最后一次修改人">
                                <Input name="updateName" disabled/>
                            </FormItem>
                            <FormItem {...formItemLayout_two} label="最后一次时间">
                                <Input name="updateTime" disabled/>
                            </FormItem>
                            <FormItem colSpan={12} style={{marginLeft:'35%'}}>
                                <Box spacing={8} direction="row" align="center">
                                    <Form.Submit type="primary" onClick={this.onSubmit} validate>提交</Form.Submit>
                                    <Button onClick={this.onClose} type="secondary">取消</Button>
                                </Box>
                            </FormItem>
                        </Form>
                    </Card.Content>
                    </Card>
                </Dialog>
            </div>
        );
    }
}
export default AddExamPaperQuestion;

